package com.winit.openapi.ups.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.winit.ums.spi.user.UserBusinessConfService;
import com.winit.ums.spi.user.command.VildaiteIntelligentRecommendCommand;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.spi.SPIException;
import com.winit.common.spi.command.SPICommand;
import com.winit.common.spi.context.CommandContext;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;
import com.winit.ums.spi.UmsCustomerService;
import com.winit.ums.spi.commnad.IdCommand;
import com.winit.ums.spi.commnad.customer.QueryCompanylCommand;
import com.winit.ums.spi.user.UserBusinessConfService;
import com.winit.ums.spi.user.command.VildaiteIntelligentRecommendCommand;
import com.winit.ums.spi.vo.CustomerInfoVO;
import com.winit.ups.spi.command.CodeCommand;
import com.winit.ups.spi.command.QueryAutoTaketimeCommand;
import com.winit.ups.spi.command.QueryWarehouseByTypesCommand;
import com.winit.ups.spi.sys.ConfigService;
import com.winit.ups.spi.sys.command.QueryByCategoryCodeCommand;
import com.winit.ups.spi.sys.vo.MultipleConfigVo;
import com.winit.ups.spi.warehouse.StorageWarehouseService;
import com.winit.ups.spi.warehouse.WarehouseService;
import com.winit.ups.spi.warehouse.command.AddMerchandiseTransferConfigCommand;
import com.winit.ups.spi.warehouse.command.AddWarehouseTransferRuleCommand;
import com.winit.ups.spi.warehouse.command.IfCustomerOpenStorageServiceCommand;
import com.winit.ups.spi.warehouse.command.IfOpenStorageCommand;
import com.winit.ups.spi.warehouse.command.PageMerchandiseTransferConfigCommand;
import com.winit.ups.spi.warehouse.command.PageWarehouseTransferRuleCommand;
import com.winit.ups.spi.warehouse.command.QueryWarehouseCountryCommand;
import com.winit.ups.spi.warehouse.vo.CountryWarehouseVo;
import com.winit.ups.spi.warehouse.vo.MerchandiseTransferConfigVo;
import com.winit.ups.spi.warehouse.vo.StorageCountryVo;
import com.winit.ups.spi.warehouse.vo.WarehouseTransferRuleVo;
import com.winit.ups.spi.warehouse.vo.WarehouseVo;


@Controller
@RequestMapping(value = "/ups/warehouse")
public class UpsWarehouseController extends BaseController {

    @Resource
    private WarehouseService upsWarehouseService;
    
    @Resource
    private ConfigService upsConfigService;


   @Resource
    private StorageWarehouseService upsStorageWarehouseService;

    @Resource
    private UmsCustomerService umsCustomerService;

    @Resource
    private UserBusinessConfService userBusinessConfService;
	
    @RequestMapping(value = "/queryWarehouseByCode")
    public String queryWarehouseByCode(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        CodeCommand command = new CodeCommand();

        String warehouseCode = (String) json.get("warehouseCode");
        command.setCode(warehouseCode);
        if (StringUtils.isNotBlank(warehouseCode)) {
            WarehouseVo warehouseVo = upsWarehouseService.queryWarehouseByCode(command);
            responseMsg.setData(warehouseVo);
        }

        return SUCCESS;
    }

    /**
     * 根据类型查询仓库
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryWarehouseByType")
    public String queryWarehouseByType(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        CodeCommand command = new CodeCommand();

        String warehouseTypeCode = (String) json.get("warehouseTypeCode");
        command.setCode(warehouseTypeCode);
        if (StringUtils.isNotBlank(warehouseTypeCode)) {
            List<WarehouseVo> warehouseVos = upsWarehouseService.queryWarehouseByType(command);
            responseMsg.setData(warehouseVos);
        }

        return SUCCESS;
    }
    
    
    /**
     * 根据类型查询仓库
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryCountryByWarehouseType")
    public String queryCountryByWarehouseType(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        QueryWarehouseCountryCommand command = new QueryWarehouseCountryCommand();
        String warehouseTypeCode = (String) json.get("wareHouseType");
        command.setWarehouseType(warehouseTypeCode);
        if (StringUtils.isNotBlank(warehouseTypeCode)) {
            //获取客户编码
            CustomerInfoVO contextCustomerInfo = getContextCustomerInfo();
            //判断该客户是否开启了仓群
            VildaiteIntelligentRecommendCommand vildaiteCommand = new VildaiteIntelligentRecommendCommand();
            vildaiteCommand.setUserCode(contextCustomerInfo.getCode());
            vildaiteCommand.setClassCode("WAREHOUSEGROUPMANAGER");
            boolean flag = userBusinessConfService.vildaiteIntelligentRecommend(vildaiteCommand);
            if(flag){
                command.setIsOpenWarehouseGroup("Y");
            }
            List<CountryWarehouseVo> warehouseVos = upsWarehouseService.queryWarehouseCountryTransferPLSC(command);
            responseMsg.setData(warehouseVos);
        }

        return SUCCESS;
    }
    
    
    
    /**
     * 根据类型查询仓库，支持多个类型
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryWarehouseByTypes")
    public String queryWarehouseByTypes(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        
       if( !ValidateUtil.isExistValue(json, "types")){
           //直接返回空
           responseMsg.setData(null);
           return SUCCESS;
       }
       
       QueryWarehouseByTypesCommand command = JSON.parseObject(requestMsg.getData().toString(),QueryWarehouseByTypesCommand.class);
      
        if (null != command.getTypes() && command.getTypes().size() > 0) {
            List<WarehouseVo> warehouseVos = upsWarehouseService.queryWarehouseByTypesIntersect(command);
            responseMsg.setData(warehouseVos);
        }

        return SUCCESS;
    }
    
    
    
    /**
     * 根据仓库编码查询仓库所在地的自提时间
     * 返回自提时间，格式   2016-07-07;2016-07-08;12:00-14:00 备：已“;”隔开，前面两个为日期，后一个为时间段
     * @param requestMsg
     * @param responseMsg
     * @return ""
     */
    @RequestMapping(value = "/queryAutoTaketimeByCode")
    public String queryAutoTaketimeByCode(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) throws SPIException, Throwable {

    	// 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        QueryAutoTaketimeCommand command = new QueryAutoTaketimeCommand();

        String warehouseCode = (String) json.get("warehouseCode");
        command.setWarehouseCode(warehouseCode);
        if (StringUtils.isNotBlank(warehouseCode)) {
           String takeTime= upsWarehouseService.automaticPickUp(command);
           responseMsg.setData(takeTime);
        }
        return SUCCESS;
    }
    
    
    
    /**
     * 根据国家code（可能是多个code）查询仓库列表
     * 返回仓库列表集合
     * @param requestMsg
     * @param responseMsg
     * @return ""
     */
    @RequestMapping(value = "/queryWarehouseByCountryCode")
    public String queryWarehouseByCountryCode(@ModelAttribute RequestMsg requestMsg,@ModelAttribute ResponseMsg responseMsg) throws SPIException,Throwable {
    
        List<WarehouseVo> warehouseList=new ArrayList<WarehouseVo>();
        // 获取参数
        String codes = (String) JSONObject.parseObject(requestMsg.getData().toString()).get("countryCode");

        if(StringUtils.isNotBlank(codes)){
             String[] countryCodes= codes.split(",");
             for(String countryCode:countryCodes){
                CodeCommand command=new CodeCommand();
                command.setCode(countryCode);
                List<WarehouseVo> list=upsWarehouseService.queryWarehouseByCountryCode(command);
                if(list!=null&&list.size()>0){
                   warehouseList.addAll(list);
                }
             }
             responseMsg.setData(warehouseList);
        }
        return SUCCESS;
       
    }
	
	/**
     * 根据仓库code查询该仓库所在国家的下的退货仓库
     * 返回仓库列表集合
     * @param requestMsg
     * @param responseMsg
     * @return ""
     */
	@RequestMapping(value = "/queryWarehouseList")
	public String queryWarehouseListByCode(@ModelAttribute RequestMsg requestMsg,@ModelAttribute ResponseMsg responseMsg) throws SPIException,Throwable {
		List<WarehouseVo> WarehouseList=new ArrayList<WarehouseVo>();
		// 获取参数
		String warehouseCode = (String) JSONObject.parseObject(requestMsg.getData().toString()).get("warehouseCode");
		String customerCode = (String) JSONObject.parseObject(requestMsg.getData().toString()).get("customerCode");
		if(StringUtils.isNotBlank(warehouseCode)){
			if("PLSC".equals(warehouseCode)){
				CodeCommand queryWarehosueCommand = new CodeCommand();
				queryWarehosueCommand.setCode(warehouseCode);
				WarehouseVo warehouseVo = upsWarehouseService.queryWarehouseByCode(queryWarehosueCommand);
				WarehouseList.add(warehouseVo);
				responseMsg.setData(WarehouseList);
			}else{
				CodeCommand command=new CodeCommand ();
	        	command.setCode(warehouseCode);
	        	command.setCustomerCode(customerCode);
	        	WarehouseList=upsWarehouseService.queryWarehouseListByWarehouseCode(command);
		        responseMsg.setData(WarehouseList);
			}
		}
        return SUCCESS;
	}
	
	/**
     * 查询退货仓库（曾经是退货仓和现在是退货仓库）
     * 返回仓库编码和仓库名称
     * @param requestMsg
     * @param responseMsg
     * @return ""
     */
	@RequestMapping(value = "/queryReturnWarehouse")
	public String queryReturnWarehouse(@ModelAttribute RequestMsg requestMsg,@ModelAttribute ResponseMsg responseMsg) throws SPIException,Throwable {
		List<WarehouseVo> WarehouseList=new ArrayList<WarehouseVo>();
		//临时方式，新增波兰仓
		WarehouseVo plWarehouseVo = new WarehouseVo();
		plWarehouseVo.setCode("PLSC");
		plWarehouseVo.setName("PLSC Warehouse");
		WarehouseList.add(plWarehouseVo);
		QueryByCategoryCodeCommand command = new QueryByCategoryCodeCommand();
        command.setCategoryCode("RETURNWAREHOUSE");
        List<MultipleConfigVo> listData = upsConfigService.queryByCategoryCode(command);
		for (int i = 0; i < listData.size(); i++) {
			CodeCommand warehousCommand = new CodeCommand();
			warehousCommand.setCode(listData.get(i).getCode());
			WarehouseVo warehouseVo = upsWarehouseService.queryWarehouseByCode(warehousCommand);
			WarehouseList.add(warehouseVo);
		}
        responseMsg.setData(WarehouseList);
        return SUCCESS;
	}


    /**
     * 根据仓库编码客户编码查询仓库是否开通存储仓
     * @param requestMsg
     * @param responseMsg
     * @return
     * @throws SPIException
     * @throws Throwable
     */
    @RequestMapping(value = "/queryIfOpenStorage")
    public String ifOpenStorage(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) throws SPIException, Throwable {
        IfOpenStorageCommand command = JSON.parseObject(requestMsg.getData().toString(), IfOpenStorageCommand.class);
        command.setCtx(CommandContext.getContext());
        boolean ifStorageWarehouse = upsStorageWarehouseService.ifOpenStorage(command);
        responseMsg.setData(ifStorageWarehouse);
        return SUCCESS;
    }

    /**
     * 根据客户编码查询是开通存储仓服务
     * @param requestMsg
     * @param responseMsg
     * @return
     * @throws SPIException
     * @throws Throwable
     */
    @RequestMapping(value = "/queryIfCustomerOpenStorage")
    public String ifCustomerOpenStorageService(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) throws SPIException, Throwable {
        IfCustomerOpenStorageServiceCommand command = JSON.parseObject(requestMsg.getData().toString(), IfCustomerOpenStorageServiceCommand.class);
        command.setCustomerCode(this.getContextCustomerInfo().getCode());
        boolean ifCustomerOpenStorageService = upsStorageWarehouseService.ifCustomerOpenStorageService(command);
        responseMsg.setData(ifCustomerOpenStorageService);
        return SUCCESS;
    }

    /**
     * 获取所有开通存储仓业务国家
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryAllStorageCountry")
    public String getAllStorageCountry(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        SPICommand command = JSON.parseObject(requestMsg.getData().toString(), SPICommand.class);
        List<StorageCountryVo> vos = upsStorageWarehouseService.getAllStorageCountry(command);
        responseMsg.setData(vos);
        return SUCCESS;
    }

    /**
     * 新增客户的存储仓调拨规则
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/addWarehouseTransferRule")
    public String addWarehouseTransferRule(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        AddWarehouseTransferRuleCommand command = JSON.parseObject(requestMsg.getData().toString(), AddWarehouseTransferRuleCommand.class);
        command.setCustomerCode(this.getContextCustomerInfo().getCode());
        upsStorageWarehouseService.addWarehouseTransferRule(command);
        return SUCCESS;
    }

    /**
     * 编辑客户存储仓调拨配置
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/updateWarehouseTransferRule")
    public String updateWarehouseTransferRule(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        AddWarehouseTransferRuleCommand command = JSON.parseObject(requestMsg.getData().toString(), AddWarehouseTransferRuleCommand.class);
        command.setCustomerCode(this.getContextCustomerInfo().getCode());
        upsStorageWarehouseService.updateWarehouseTransferRule(command);
        return SUCCESS;
    }

    /**
     * 失效删除客户存储仓调拨配置
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/inactiveWarehouseTransferRule")
    public String inactiveWarehouseTransferRule(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        IdCommand command = JSON.parseObject(requestMsg.getData().toString(), IdCommand.class);
        upsStorageWarehouseService.inactiveWarehouseTransferRule(command);
        return SUCCESS;
    }

    /**
     * 分页查询客户存储仓调拨配置
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/pageWarehouseTransferRule")
    public String pageWarehouseTransferRule(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        PageWarehouseTransferRuleCommand command = JSON.parseObject(requestMsg.getData().toString(), PageWarehouseTransferRuleCommand.class);
        command.setCustomerCode(this.getContextCustomerInfo().getCode());
        Page<WarehouseTransferRuleVo> page = upsStorageWarehouseService.pageWarehouseTransferRule(command);
        responseMsg.setData(page);
        return SUCCESS;
    }

    /**
     * 新增客户商品调拨配置
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/addMerchandiseTransferConfig")
    public String addMerchandiseTransferConfig(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        AddMerchandiseTransferConfigCommand command = JSON.parseObject(requestMsg.getData().toString(), AddMerchandiseTransferConfigCommand.class);
        command.setCustomerCode(this.getContextCustomerInfo().getCode());
        upsStorageWarehouseService.addMerchandiseTransferConfig(command);
        return SUCCESS;
    }

    /**
     * 更新客户商品调拨配置
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/updateMerchandiseTransferConfig")
    public String updateMerchandiseTransferConfig(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        AddMerchandiseTransferConfigCommand command = JSON.parseObject(requestMsg.getData().toString(), AddMerchandiseTransferConfigCommand.class);
        command.setCustomerCode(this.getContextCustomerInfo().getCode());
        upsStorageWarehouseService.updateMerchandiseTransferConfig(command);
        return SUCCESS;
    }

    /**
     * 失效删除客户商品调拨配置
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/inactiveMerchandiseTransferConfig")
    public String inactiveMerchandiseTransferConfig(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        IdCommand command = JSON.parseObject(requestMsg.getData().toString(), IdCommand.class);
        upsStorageWarehouseService.inactiveMerchandiseTransferConfig(command);
        return SUCCESS;
    }

    /**
     * 分页查询客户商品调拨配置
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/pageMerchandiseTransferConfig")
    public String pageMerchandiseTransferConfig(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        PageMerchandiseTransferConfigCommand command = JSON.parseObject(requestMsg.getData().toString(), PageMerchandiseTransferConfigCommand.class);
        command.setCustomerCode(this.getContextCustomerInfo().getCode());
        Page<MerchandiseTransferConfigVo> page = upsStorageWarehouseService.pageMerchandiseTransferConfig(command);
        responseMsg.setData(page);
        return SUCCESS;
    }


    /** 从上下文中获取客户信息 */
    private CustomerInfoVO getContextCustomerInfo() {
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if(customer == null) {
            throw new ApiException(ErrorCode.SYSTEM_ERROR);
        }
        return customer;
    }
}
